import { useEffect, useRef, useState } from 'react'
import NavBar from '../../components/Navbar'
import { Mask, Popup, ProgressBar, Swiper, Toast } from 'antd-mobile'
import './index.less'
import { ToPay, Vip2Data } from '../../api/mine'
import { getAuthentication, getVersion, isIOS } from '../../utils/util'
import appSdk from '../../utils/app_sdk'
import { useNavigate } from 'react-router-dom'

const colors = ['#ace0ff', '#bcffbd', '#e4fabd', '#ffcfac', '#e4fabd', '#ffcfac']
const appStoreKey = 'appstoreAM'

export default function VipCenter() {
  const swiperRef = useRef()
  const navigate = useNavigate()
  const [selectLevel, setSelectLevel] = useState(1)
  const [payVisible, setPayVisible] = useState(false)
  const [selectIndex, setSelectIndex] = useState(0)
  const [selectWay, setSelectWay] = useState('aliPay')
  const [isAppstore, setIsAppstore] = useState(getAuthentication('packageChannel') === appStoreKey)

  const [vipDetail, setVipDetail] = useState({ vipLevel: 0, vip_auth: [], vip_goods: [], endTime: '', vipExp: 0, diff: 0, reward: [] })

  const requestInfo = () => {
    Toast.show({ icon: 'loading' })
    Vip2Data({ system: isIOS ? 2 : 1 })
      .then((res) => {
        console.log(res)
        setVipDetail({
          ...res.data
          // vipLevel: 0
        })
        setTimeout(() => {
          swiperRef.current.swipeTo(res.data?.vipLevel - 1 <= 0 ? 0 : res.data?.vipLevel - 1)
          setSelectLevel(+res.data?.vipLevel || 1)
        }, 100)
      })
      .finally(() => {
        Toast.clear()
      })
  }

  useEffect(() => {
    console.log(
      `%c Version = ${getVersion() || '1.0.0'} 'packageChannel =>', ${getAuthentication('packageChannel')} %c`,
      'background:#41b883 ; padding: 4px; border-radius: 4px;  color: #fff',
      'background:transparent'
    )
    requestInfo()
  }, [])

  const [showItem, setShowItem] = useState({})
  const [detailVisiable, setDetailVisiable] = useState(false)
  const showDetail = (item) => {
    setShowItem(item)
    setDetailVisiable(true)
  }

  const toPay = () => {
    Toast.show({ icon: 'loading', content: '正在支付中...', maskClickable: false })
    if (!isAppstore) {
      ToPay({ goods_id: vipDetail.vip_goods[selectIndex]?.id, type: selectWay === 'aliPay' ? 1 : 2 }).then((res) => {
        console.log('支付信息', res.data)
        appSdk(selectWay, res.data, (result) => {
          console.log('成功回调，拿到的参数是', result)
          requestInfo()
          const data = typeof result === 'string' ? JSON.parse(result) : result
          Toast.show({
            icon: data.status === 'success' ? 'success' : 'fail',
            content: data.status === 'success' ? '支付成功' : data?.message || '支付失败'
          })
        })
      })
    } else {
      appSdk(
        'appStorePay',
        {
          id: vipDetail.vip_goods[selectIndex]?.id,
          good_id: vipDetail.vip_goods[selectIndex]?.good_id
        },
        (result) => {
          console.log('appstore 成功回调，拿到的参数是', result)
          requestInfo()
          if (typeof result === 'string') {
            const data = JSON.parse(result)
            Toast.show({
              // icon: data.status === "success" ? "success" : "fail",
              content: data.status === 'success' ? '支付成功' : data?.message || '支付失败'
            })
          }
          if (typeof result === 'object') {
            const data = result
            Toast.show({
              // icon: data.status === "success" ? "success" : "fail",
              content: data.status === 'success' ? '支付成功' : data?.message || '支付失败'
            })
          }
        }
      )
    }
  }

  const [selectTab, setSelectTab] = useState(1)

  return (
    <div className="vip_center_wrap">
      <NavBar
        title="VIP中心"
        other={
          <div
            className="detail_icon"
            onClick={() => {
              navigate(`/vip_center_detail`)
            }}
          ></div>
        }
      />
      <div>
        <Swiper
          ref={swiperRef}
          onIndexChange={(idx) => setSelectLevel(idx + 1)}
          indicator={() => null}
          slideSize={86}
          trackOffset={7}
          stuckAtBoundary={false}
          // defaultIndex={selectLevel}
        >
          {colors.map((color, index) => (
            <Swiper.Item key={index}>
              <div className="content">
                <div className="info">
                  <div className="flex">
                    <div className={`level_icon level_${index + 1}`}></div>
                    <div className="ext">
                      {vipDetail.vipLevel === index + 1 && vipDetail.vipLevel <= 5 && <div className="time">{vipDetail.endTime} 到期</div>}
                      <div
                        className={`lock_status ${vipDetail.vipLevel >= index + 1 ? 'on' : 'un'}_${index + 1}`}
                        // style={{
                        // 	background: "url(../../images/vip/un_v2.png) no-repeat"
                        //  }}
                      ></div>
                    </div>
                  </div>
                  {vipDetail.vipLevel === 0 && (
                    <div className="un_open">
                      尚未开通VIP会员 <span onClick={() => setPayVisible(true)}>立即开通&gt;</span>
                    </div>
                  )}
                  {vipDetail.vipLevel < index + 1 && vipDetail.vipLevel !== 0 && index <= 4 && (
                    <div className="un_open">
                      尚未解锁Lv{index + 1}权益 <span onClick={() => setPayVisible(true)}>提升等级&gt;</span>
                    </div>
                  )}
                  {index === 5 && <div className="un_open">更多VIP等级敬请期待</div>}
                  {vipDetail.vipLevel > index + 1 && <div className="un_open">已达成该等级</div>}
                  {+vipDetail.vipLevel === index + 1 && vipDetail.vipLevel <= 5 && (
                    <div className="progress">
                      <div className="progress_data">
                        <span>{`${vipDetail.vipExp}/${vipDetail.vipExp + vipDetail.diff}`}</span>
                        <ProgressBar
                          percent={(vipDetail.vipExp / (vipDetail.vipExp + vipDetail.diff)) * 100}
                          style={{
                            '--fill-color': 'linear-gradient(to left, #FFFFFF 0%, rgba(255, 255, 255, 0) 97.22%)',
                            '--track-color': 'rgba(255,255,255,0.2)',
                            padding: '4px 0 4px 0'
                          }}
                        />
                        <span>
                          距Lv{vipDetail.vipLevel + 1}还差{vipDetail.diff}成长值
                        </span>
                      </div>
                    </div>
                  )}
                </div>
                <div className={`img img_${index + 1}`}></div>
              </div>
            </Swiper.Item>
          ))}
        </Swiper>
        <div className="line">
          <div className={`point ${selectLevel === 1 ? 'none' : ''}`}>
            <div className="p"></div>
            <div className="t">Lv{selectLevel === 1 ? '' : selectLevel - 1}</div>
          </div>
          <div className="point">
            <div className="p"></div>
            <div>Lv{selectLevel}</div>
          </div>
          <div className={`point ${selectLevel === 6 ? 'none' : ''}`}>
            <div className="p"></div>
            <div className="t">Lv{selectLevel + 1 === 6 ? '6+' : selectLevel + 1}</div>
          </div>
          {/* <div className="bg"></div> */}
        </div>
      </div>
      <div className="tabs">
        <div className={`tab ${selectTab === 1 ? 'active' : ''}`} onClick={() => setSelectTab(1)}>
          贵族特权
        </div>
        <div className={`tab ${selectTab === 2 ? 'active' : ''}`} onClick={() => setSelectTab(2)}>
          装扮特权
        </div>
      </div>
      {selectTab === 1 && (
        <div className={`item_content left ${vipDetail.vip_auth.length >= 7 ? 'need_height' : ''}`}>
          {vipDetail.vip_auth?.map((item, idx) => (
            <div className="item" onClick={() => showDetail(item)}>
              <div className="box">
                <div className="icon">
                  <img src={selectLevel >= item.level ? item.img : item.unlock_img} alt="" />
                </div>
              </div>
              <div className="name">{item.title}</div>
              <div className="lv">
                Lv{item.level}
                {vipDetail.vipLevel >= item.level ? '已' : '未'}解锁
              </div>
            </div>
          ))}
        </div>
      )}
      {selectTab === 2 && (
        <div className={`item_content right ${vipDetail.reward.length >= 7 ? 'need_height' : ''}`}>
          {vipDetail.reward?.map((item) => (
            <div className={`item ${item.level <= selectLevel ? '' : 'lock'}`}>
              <div className="box">
                <div className="icon">
                  <img src={item.show_img} alt="" />
                </div>
                {item.level > selectLevel && <div className="lock_icon"></div>}
              </div>
              <div className="name">{item.name}</div>
              <div className="lv">
                Lv{item.level}
                {vipDetail.vipLevel >= item.level ? '已' : '未'}解锁
              </div>
            </div>
          ))}
        </div>
      )}
      <div className="pay_btn" onClick={() => setPayVisible(true)}>
        {Boolean(vipDetail.vipLevel) ? '立刻提升会员等级' : '立刻开通会员等级'}
      </div>

      <Mask visible={detailVisiable} onMaskClick={() => setDetailVisiable(false)}>
        {/* <div className='detail_content'>
					<div className="title">{showItem?.title}</div>
					<div className="desc">{showItem?.desc}</div>
					<div className="img">
						<img src={showItem?.explain_img} alt="" />
					</div>
				</div> */}
        <div className="content_img">
          <img src={showItem?.explain_img} alt="" />
        </div>
      </Mask>

      <Popup
        visible={payVisible}
        onMaskClick={() => {
          setPayVisible(false)
        }}
        bodyStyle={{
          borderTopLeftRadius: '8px',
          borderTopRightRadius: '8px',
          minHeight: '40vh',
          borderTop: '1px solid #FFDA93',
          backgroundColor: '#000',
          color: '#fff',
          padding: '20px 16px 0 16px',
          height: 356,
          boxSizing: 'border-box'
        }}
      >
        {/* {mockContent} */}
        <div className="pay_content">
          <div className="tit">VIP开通</div>
          <div className="items">
            {vipDetail.vip_goods.map((item, idx) => (
              <div className={`item ${idx === selectIndex ? 'active' : ''}`} key={item.id} onClick={() => setSelectIndex(idx)}>
                <div className="t">{item.desc}</div>
                <div className="price">
                  <span className="currency">¥</span>
                  <span className="num">{Number(item.price).toFixed(1)}</span>
                </div>
                <div className="send">{`${item.exp ? `+${item.exp}经验值` : ''}`}</div>
              </div>
            ))}
          </div>
          <div className="pay_way_wrap" style={{ marginTop: 18 }}>
            <div className="content-data" style={{ display: isAppstore ? 'none' : '' }}>
              <p>选择支付方式</p>
              <div className="items">
                <div className="pay_item" onClick={() => setSelectWay('wechatPay')}>
                  <div className={`circle ${selectWay === 'wechatPay' ? 'active' : ''}`}></div>
                  {/* <div className="icon wechat"></div> */}
                  <div className="txt">微信支付</div>
                </div>
                <div className="pay_item" onClick={() => setSelectWay('aliPay')}>
                  <div className={`circle ${selectWay === 'aliPay' ? 'active' : ''}`}></div>
                  {/* <div className="icon ali"></div> */}
                  <div className="txt">支付宝</div>
                </div>
              </div>
            </div>
            <div className="pay-tip" style={{ fontSize: '12px', paddingTop: 4, lineHeight: '24px' }}>
              开通会员代表接受
              <span>
                <a href={`${window.baseConfig.baseUrl}/protocol/sla`} style={{ textDecoration: 'none' }}>
                  《{window.baseConfig.package_name}会员服务协议》
                </a>
              </span>
            </div>
            <div className="pay_button" onClick={toPay}>
              <p>{`¥${vipDetail.vip_goods[selectIndex]?.price} 立刻开通`}</p>
            </div>
          </div>
        </div>
      </Popup>
    </div>
  )
}
